package com.xhwl.centiotdata.suppliersystem.sinoiov;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author pengjunming
 * @description
 * @date 2022/11/9 10:16
 */
@Service
@Slf4j
public class RegionSinoiovHandler {

    public String add(PedestrianIntegrationConfigDTO config, Organization org, OrgInfo parent) {
        JSONObject param = new JSONObject();
        param.put("agentName", org.getName());
        param.put("agentCode", org.getId());
        if (Objects.nonNull(parent)) {
            param.put("parentAgentId", parent.getOrgIndexCode());
        } else {
            param.put("parentAgentId", "1");
        }
        try {
            String createUrl = "/api/thirdParty/createAgentExt";
            String jsonResult = HttpUtil.post(config.getIpAndPort() + createUrl, param.toString());
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            if (Objects.equals(jsonObject.getString("returnCode"), "Y")) {
                JSONObject orgInfo = jsonObject.getJSONObject("obj");
                return orgInfo.getString("agentId");
            }
        } catch (Exception e) {
            log.error("中交兴路组织数据同步异常", e);
        }
        return null;
    }

    public boolean delete(PedestrianIntegrationConfigDTO config, String agentId) {
        JSONObject param = new JSONObject();
        param.put("agentId", agentId);
        try {
            String deleteUrl = "/api/thirdParty/deleteAgentExt";
            String jsonResult = HttpUtil.post(config.getIpAndPort() + deleteUrl, param.toString());
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            if (Objects.equals(jsonObject.getString("returnCode"), "Y")) {
                return true;
            } else {
                log.error("删除中交兴路组织数据失败:{}", jsonResult);
            }
        } catch (Exception e) {
            log.error("删除中交兴路组织数据异常", e);
        }
        return false;
    }

    public void update(PedestrianIntegrationConfigDTO config, Organization org, OrgInfo orgInfo) {
        JSONObject param = new JSONObject();
        param.put("agentName", org.getName());
        param.put("agentId", orgInfo.getOrgIndexCode());
        try {
            String createUrl = "/api/thirdParty/createAgentExt";
            String jsonResult = HttpUtil.post(config.getIpAndPort() + createUrl, param.toString());
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            if (!Objects.equals(jsonObject.getString("returnCode"), "Y")) {
                log.error("更新组织失败");
            }
        } catch (Exception e) {
            log.error("中交兴路组织数据同步异常", e);
        }
    }
}
